<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import wsjzglService from '@/api/wsjzgl'
import axios from '@/request/http'
import { useMainStore } from '@/store/main'
import detailItem from '@/views/gdgl/jcgsh/component/gdzl/ajwjgl/components/detail-item.vue'
import { useRoute } from 'vue-router'
const route = useRoute()
const emit = defineEmits(['refresh'])

const store = useMainStore()

const isLoading = ref(false)
const createLoading = ref(false)
const wjList = ref<any[]>([])
const wjbhList = ref<string[]>([])

//打开窗口
const dialogVisible = ref(false)
const openDialog = (data: any) => {
  wjList.value = data
  wjbhList.value = data.map((item: any) => item.wjbh)
  const params = {
    ajbh: store.$state.nodeTreeData?.ajbh,
    mlbh: store.$state.nodeTreeData?.bh,
    wjbhList: data.map((item: any) => item.wjbh),
  }
  request(params)
  dialogVisible.value = true
}

// 获取当前文件目录
const request = (params: any) => {
  createLoading.value = true
  wsjzglService
    .createAjwjml(params, route.query.ajbh as string)
    .then((res) => {
      if (res.data.mlxxList.length) {
        tableData.value = res.data.mlxxList.map((item) => {
          return {
            jswjsxh: item.jsy,
            kswjsxh: item.ksy,
            mlmc: item.mltm,
            mlscrq: item.bmwcrq,
            mlsxh: item.mlsxh,
            wh: item.mlwh,
            wjbhList: item.wjbhList,
            zrz: item.zrz,
          }
        })
      } else {
        tableData.value = [
          {
            jswjsxh: 1,
            kswjsxh: 1,
            mlmc: '',
            mlscrq: '',
            mlsxh: 0,
            wh: '',
            wjbhList: [],
            zrz: '',
          },
        ]
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      createLoading.value = false
    })
}

// 保存目录
const save = () => {
  if (!validatePage()) return
  const params = {
    ajbh: store.$state.nodeTreeData?.ajbh,
    mlbh: store.$state.nodeTreeData?.bh,
    mlxxList: tableData.value.map((el, i) => ({
      ...el,
      mlsxh: i + 1,
      wjbhList: wjbhList.value.slice(el.kswjsxh - 1, el.jswjsxh),
    })),
  }
  isLoading.value = true
  wsjzglService
    .saveAjbmjg(params, route.query.ajbh as string)
    .then(() => {
      ElMessage({
        type: 'success',
        message: '保存成功',
      })
      emit('refresh')
      closeDialog()
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      isLoading.value = false
    })
}

/*
 * 关闭弹框
 */
const closeDialog = () => {
  dialogVisible.value = false
  tableData.value = []
  wjList.value = []
  wjbhList.value = []
  closeDetail(false)
}

const tableData = ref<any[]>([])

// 上方插入行
const sfcrhFn = (ksy: number, index: number) => {
  if (index === 0) {
    tableData.value.unshift({
      bmwcrq: '',
      mlsxh: index,
      mltm: '',
      mlwh: '',
      wjbhList: [],
      zrz: '',
    })
    return
  }
  // 当前行结束页小于总页数则可以添加
  tableData.value.splice(index, 0, {
    bmwcrq: '',
    mlsxh: index,
    mltm: '',
    mlwh: '',
    wjbhList: [],
    zrz: '',
  })
}

// 下方插入行
const xfcrhFn = (jsy: number, index: number) => {
  // 当前行结束页小于总页数则可以添加
  tableData.value.splice(index + 1, 0, {
    bmwcrq: '',
    mlsxh: index + 1,
    mltm: '',
    mlwh: '',
    wjbhList: [],
    zrz: '',
  })
}
// 删除行
const schFn = (index: number) => {
  tableData.value.splice(index, 1)
}

const validatePage = () => {
  tableData.value.forEach((el) => {
    const wjPart = wjbhList.value.slice(el.kswjsxh - 1, el.jswjsxh)
    el.wjbhList = wjPart
  })
  let tempWjList: string[] = []
  for (let i = 0; i < tableData.value.length; i++) {
    if (!tableData.value[i].mlmc) {
      ElMessage({ type: 'warning', message: `序号${i + 1}的目录题名为空` })
      return false
    }
    const ksy = tableData.value[i].kswjsxh
    const jsy = tableData.value[i].jswjsxh
    if (!ksy) {
      ElMessage({ type: 'warning', message: `序号${i + 1}的开始页为空` })
      return false
    }
    if (!jsy) {
      ElMessage({ type: 'warning', message: `序号${i + 1}的结束页为空` })
      return false
    }
    if (ksy !== undefined && jsy !== undefined && ksy <= jsy) {
      const wjPart = wjbhList.value.slice(ksy - 1, jsy)
      if (wjPart.some((bh) => tempWjList.includes(bh))) {
        ElMessage({ type: 'warning', message: `序号${i + 1}的目录下中的文件与其他目录重叠` })
        return false
      }
    }
    if (ksy !== undefined && jsy !== undefined && ksy > jsy) {
      ElMessage({ type: 'warning', message: `序号${i + 1}的目录开始页大于结束页` })
      return false
    }
    tempWjList = [...tempWjList, ...tableData.value[i].wjbhList]
  }
  return true
}

// 预览模式
const previewMode = ref(false)
const currentIndex = ref(0)
const loadDetail = (index: any) => {
  previewMode.value = true
  currentIndex.value = index
}
const closeDetail = (val: boolean) => {
  if (!val) {
    previewMode.value = false
  } else {
    previewMode.value = true
  }
  currentIndex.value = 0
}

const indexChange = (index: number) => {
  currentIndex.value = index
}
defineExpose({ openDialog })
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    title="编目"
    width="90%"
    :close-on-click-modal="false"
    :before-close="closeDialog"
  >
    <div class="dialog-content">
      <div class="left-box">
        <div class="left-header">
          <div class="title">待编目材料</div>
          <div>
            预览模式：
            <el-switch
              v-model="previewMode"
              style="--el-switch-on-color: #13ce66"
              @change="closeDetail"
            />
          </div>
        </div>
        <!-- 展示详情 -->
        <detail-item
          v-if="previewMode"
          isBm
          :current-index="currentIndex"
          class="detail-wrapper"
          :wjxqxxList="wjList"
          @indexChange="indexChange"
        ></detail-item>
        <div v-else class="writings-box">
          <div class="writings-item" v-for="(item, index) in wjList" :key="item.wjbh">
            <div class="item-content">
              <div class="content-img" @dblclick.stop="loadDetail(index)">
                <img
                  :src="
                    axios.defaults.baseURL +
                    '/fpi/wjfw/download?wjbh=' +
                    item.jpgwjxh +
                    '&date=' +
                    Date.now()
                  "
                />
              </div>
              <div class="content-footer" v-if="item.jcztmc && item.jcztdm !== 'gd0490001'">
                {{ item.jcztmc }}
              </div>
            </div>
            <div class="pageNumber">{{ index + 1 }}</div>
          </div>
        </div>
      </div>
      <div class="right-box">
        <div class="left-header">目录信息</div>
        <div class="table-box">
          <el-table height="100%" :data="tableData" v-loading="createLoading">
            <el-table-column type="index" label="序号" width="55" />
            <el-table-column label="题名" width="240">
              <template #default="scope">
                <el-input v-model="scope.row.mlmc" maxlength="30" />
              </template>
            </el-table-column>
            <el-table-column label="文号" width="140">
              <template #default="scope">
                <el-input v-model="scope.row.wh" />
              </template>
            </el-table-column>
            <el-table-column label="责任者" width="140">
              <template #default="scope">
                <el-input v-model="scope.row.zrz" />
              </template>
            </el-table-column>
            <el-table-column label="日期" width="160">
              <template #default="scope">
                <!-- <el-input v-model="scope.row.mlscrq" /> -->
                <el-date-picker
                  style="width: 100%"
                  v-model="scope.row.mlscrq"
                  type="date"
                  placeholder="请选择"
                  value-format="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                />
              </template>
            </el-table-column>
            <el-table-column prop="kswjsxh" label="开始页" width="90">
              <template #default="scope">
                <el-input-number
                  style="width: 100%"
                  :controls="false"
                  :min="0"
                  v-model="scope.row.kswjsxh"
                />
              </template>
            </el-table-column>
            <el-table-column prop="jswjsxh" label="结束页" width="90">
              <template #default="scope">
                <el-input-number
                  style="width: 100%"
                  :controls="false"
                  :min="0"
                  v-model="scope.row.jswjsxh"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="60" fixed="right">
              <template #default="scope">
                <el-dropdown>
                  <el-button class="action-btn" type="primary" text>
                    <img src="@/assets/images/action.png" alt="" />
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="sfcrhFn(scope.row.kswjsxh, scope.$index)"
                        >上方插入行</el-dropdown-item
                      >
                      <el-dropdown-item @click="xfcrhFn(scope.row.jswjsxh, scope.$index)"
                        >下方插入行</el-dropdown-item
                      >
                      <el-dropdown-item @click="schFn(scope.$index)">删除行</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="save" :loading="isLoading">保存目录</el-button>
        <el-button @click="closeDialog">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.dialog-content {
  width: 100%;
  height: 70vh;
  display: flex;

  .left-box {
    width: 40%;
    border-radius: 5px;
    border: solid 1px #dce5f5;
    padding: 10px;
    display: flex;
    flex-direction: column;

    .left-header {
      height: 27px;
      color: #526a89;
      font-weight: bold;
      display: flex;
      border-bottom: 1px solid #dce5f5;
      padding-bottom: 10px;
      justify-content: space-between;
      align-items: center;

      .title {
        position: relative;
        padding-left: 10px;
        &::before {
          content: '';
          position: absolute;
          width: 4px;
          height: 16px;
          background-color: #006cff;
          top: 2px;
          left: 0;
        }
      }
    }

    .writings-box {
      max-height: 100%;
      overflow: auto;
      display: flex;
      flex-wrap: wrap;
      padding-left: 5px;
      margin-top: 10px;
      .writings-item {
        width: 212px;
        padding: 0 16px 10px 0;
        display: flex;
        flex-direction: column;

        .item-content {
          display: flex;
          flex-direction: column;
          flex: 1;
          flex-shrink: 0;
          background-color: #fff;
          box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.1);

          .content-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 10px;

            img {
              width: 15px;
              height: 15px;
            }
          }

          .content-img {
            padding: 0 10px;
            flex: 1;
            flex-shrink: 0;
            background-color: #fff;
            cursor: pointer;
            & > img {
              width: 100%;
              height: 212px;
            }
          }

          .content-footer {
            width: 100%;
            text-align: center;
            padding: 5px 0;
            background-color: #f7c863;
          }
        }

        .pageNumber {
          height: 26px;
          line-height: 26px;
          text-align: center;
        }
      }
    }
  }

  .right-box {
    width: 60%;
    border-radius: 5px;
    border: solid 1px #dce5f5;
    margin-left: 10px;
    padding: 10px;
    display: flex;
    flex-direction: column;

    .left-header {
      height: 16px;
      line-height: 16px;
      color: #526a89;
      font-weight: bold;
      display: flex;
      border-bottom: 1px solid #dce5f5;
      padding-bottom: 26px;

      &::before {
        content: '';
        width: 4px;
        height: 16px;
        background-color: #006cff;
        margin-right: 6px;
      }
    }

    .table-box {
      height: calc(100% - 30px);
      padding-top: 10px;
      .action-btn {
        min-width: auto;
        padding: 8px 0;
      }
    }
  }
}
</style>
